#!/usr/bin/env sh

Install_Git() 
{
  Echo_Blue "安装 Git..."

  # 判断 docker 命令是否支持
  if command -v git >/dev/null 2>&1; then
    Echo_Yellow "已安装: `git --version`"
  else
    if [ "$PM" = "yum" ]; then
      yum -y install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
      yum -y install git-core
    elif [ "$PM" = "apt" ]; then
      apt-get -y install libcurl4-gnutls-dev libexpat1-dev gettext libz-dev libssl-dev
      apt-get -y install git
    fi
  fi
}

Git_Origin_Update_Type_Selection()
{
  # 判断变量 GIT_ORIGIN_UPDATE_TYPE 是否未设置或为空字符串
  if [ -z ${GIT_ORIGIN_UPDATE_TYPE} ]; then
    GIT_ORIGIN_UPDATE_TYPE="1"
    Echo_Blue "选择项目维护方式:"
    echo "1: 本地拉取 pull (Default)"
    echo "2: 远程推送 push"
    echo "3: 开发环境"
    read -p "请选择 (1, 2, 3): " GIT_ORIGIN_UPDATE_TYPE
    case "${GIT_ORIGIN_UPDATE_TYPE}" in
      2)
        Echo_Yellow "将初始化裸仓库，由开发者主动推送更新！"
        ;;
      3)
        Echo_Yellow "开发环境下，代码由本地维护！"
        ;;
      *)
        Echo_Yellow "将初始化工作区，由使用者主动下载更新！"
        GIT_ORIGIN_UPDATE_TYPE="1"
        ;;
    esac
  elif [ "${GIT_ORIGIN_UPDATE_TYPE}" != "2" ]; then
    GIT_ORIGIN_UPDATE_TYPE="1"
  fi
}

# 初始化工作区 $远程仓库地址 $项目安装目录
Init_Git()
{
  git clone $1 $2
}

# 初始化裸仓库 $项目名称 $项目安装目录
Init_Git_Bare()
{
  Echo_Blue "安装 Git 项目: $1"

  # 仓库
  if [ -z ${GIT_DATA_PATH} ]; then
    GIT_DATA_PATH=${DATA_PATH}/git
  fi
  if [ ! -d ${GIT_DATA_PATH} ]; then
    mkdir -p ${GIT_DATA_PATH}
  fi
  echo "仓库路径: ${GIT_DATA_PATH}/$1.git"

  # 项目
  if [ -z $2 ]; then
    OBJECT_PATH=${DATA_PATH}/site/$1
  else
    OBJECT_PATH=$2
  fi
  echo "项目路径: ${OBJECT_PATH}"

  if [ -d ${GIT_DATA_PATH}/$1.git ]; then
    Echo_Red "项目已存在！"
  else
    # 初始化项目仓库(裸库)
    git init --bare ${GIT_DATA_PATH}/$1.git
  fi

  # 配置自动部署
  cat > ${GIT_DATA_PATH}/$1.git/hooks/post-receive<<EOF
#!/usr/bin/env sh
# unset 环境变量(重要)
unset GIT_DIR
# 切换到项目部署目录
cd ${OBJECT_PATH} || exit
echo "获取最新版本"
git fetch --all
echo "更新(复位)至最新版本"
git reset --hard origin/master
# 更新项目缓存
docker exec ${APP_NAME}-php-1 sh -c "/var/www/html/laravel8/cache.sh"
EOF

  # 赋予可执行权限
  chmod +x ${GIT_DATA_PATH}/$1.git/hooks/post-receive

  # 关联仓库与项目
  git clone ${GIT_DATA_PATH}/$1.git ${OBJECT_PATH}

  # 仓库地址
  SSH_URL=${SERVER_IP}
  if [ "${SSH_PORT}" != "22" ]; then
    SSH_URL=${SERVER_IP}:${SSH_PORT}
  fi
  Echo_Yellow "$1 仓库地址: ssh://${SSH_USER}@${SSH_URL}${GIT_DATA_PATH}/$1.git"
}